<template>
             <!--面包屑-->
<div style="margin-bottom: 30px">
 <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>
   
         <router-link to="/OutsourcedUnitsList">外协单位管理</router-link>
   </el-breadcrumb-item>
   <el-breadcrumb-item>新增外协单位信息</el-breadcrumb-item>
 </el-breadcrumb></div>
<el-form ref="ruleFormRef" style="max-width: 550px" :model="form" :rules="rules" label-width="auto" 
        class="demo-ruleForm" :size="formSize" status-icon>

    
      <el-form-item label="外协单位名称：" prop="outsourcedUnitsName">
        <el-input v-model="form.outsourcedUnitsName" placeholder="请输入外协单位名称" />
      </el-form-item>


      <el-form-item label="手机号：" prop="outsourcedUnitsPhone">
        <el-input v-model="form.outsourcedUnitsPhone" placeholder="请输入手机号" />
      </el-form-item>


      <el-form-item label="邮箱：" prop="outsourcedUnitsEml">
        <el-input v-model="form.outsourcedUnitsEml" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="外协地址:" prop="startingProvince">
        <el-select v-model="selectedProvince" @change="handleProvinceChange" placeholder="请选择省份" style="width: 130px;">
          <el-option v-for="item in provinces" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCity" @change="handleCityChange" placeholder="请选择城市" style="width: 130px;">
          <el-option v-for="item in cities" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
        <el-select v-model="selectedCounty" @change="handleCountyChange" placeholder="请选择区县" style="width: 130px;">
          <el-option v-for="item in counties" :key="item.provinceCode" :label="item.provinceName" :value="item.provinceCode" />
        </el-select>
      </el-form-item>

      <el-form-item label="固定电话:" prop="outsourcedUnitsTell">
        <el-input v-model="form.outsourcedUnitsTell" placeholder="请输入固定电话" />
      </el-form-item>

      <el-form-item label="备注:" prop="outsourcedUnitsNotes">
        <el-input v-model="form.outsourcedUnitsNotes" type="textarea" />
      </el-form-item>


  <el-row type="flex" justify="end">
  
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>

  </el-row>
</el-form>
      
</template>
<script lang="ts" setup>
  //外协单位地址省市区联动
interface provinc {
    provinceCode: any
    provinceName: any
    cities: any
}
interface citi {
    provinceCode: any
    provinceName: any
    cities: any
}
interface counti {
    provinceCode: any
    provinceName: any
    cities: any
}
const provinces = ref<provinc[]>([])
const cities = ref<citi[]>([])
const counties = ref<counti[]>([])
const selectedProvince = ref("")
const selectedCity = ref("")
const selectedCounty = ref("")

// 处理省份变化
const handleProvinceChange = () => {
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    if (province) {
        cities.value = province.cities;  // 更新城市列表
        selectedCity.value = '';
        selectedCounty.value = '';
        counties.value = [];
        form.startingProvince = province.provinceName; // 设置选中的省份名称
    }
}

// 处理城市变化
const handleCityChange = () => {
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    if (city) {
        counties.value = city.cities;  // 更新县列表
        selectedCounty.value = '';
        form.startingCity = city.provinceName; // 设置选中的城市名称
    }
}

// 处理县变化
const handleCountyChange = () => {
    const county = counties.value.find(c => c.provinceCode === selectedCounty.value);
    if (county) {
        form.startingCounty = county.provinceName; // 设置选中的县名称
    }
}

// 从指定 URL 获取数据
async function fetchData(url: any) {
    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (!response.ok) throw new Error('网络响应不正常');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("数据获取错误:", error);
        ElMessage({
            message: "数据加载失败，请重试。",
            type: "error"
        });
    }
}
import  { ElMessage } from 'element-plus'
// 省改变时的处理函数
const onProvinceChange = () => {
    // 清空城市和区的选择
    selectedCity.value = '';
    selectedCounty.value = '';
    counties.value = [];
    // 获取所选省的城市
    const province = provinces.value.find(p => p.provinceCode === selectedProvince.value);
    cities.value = province ? province.cities : [];
};
// 市改变时的处理函数
const onCityChange = () => {
    // 清空区的选择
    selectedCounty.value = '';
    // 获取所选市的区
    const city = cities.value.find(c => c.provinceCode === selectedCity.value);
    counties.value = city ? city.cities : [];
};
//组件
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
//变量
const form= reactive({
  "outsourcedUnitsName": "",
  "outsourcedUnitsPhone": "",
  "outsourcedUnitsEml": "",
  "startingProvince": "",
  "startingCity": "",
  "startingCounty": "",
  "outsourcedUnitsTell": "",
  "outsourcedUnitsNotes": ""
})
//方法
//添加外协单位
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//验证
const rules = reactive<FormRules>({
    outsourcedUnitsName: [
        { required: true, message: '外协单位名称不能为空', trigger: 'blur' },
        
    ],
    outsourcedUnitsPhone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
         { pattern: /^[1][3-9]\d{9}$/,message: '无效的手机号', trigger: ['blur', 'change']}
        
    ],

    outsourcedUnitsEml: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        {
          pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, // Element Plus 提供的内置邮箱验证类型
          message: '请输入有效的邮箱地址',
          trigger: ['blur', 'change']
        },
    ],
    outsourcedUnitsTell: [
        { required: true, message: '固定电话不能为空', trigger: 'blur' },
         {
          pattern: /^[0][1][0][-]\d{6}$/, // 示例正则表达式，可能需要根据实际需求调整
          message: '无效的固定电话格式',
          trigger: ['blur', 'change']
        }
        
    ],
   
   
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (valid) {
                if (form.startingProvince == "" || form.startingCity == "" || form.startingCounty == "") {
                    ElMessage.error("请选择外协单位所在的省市区")
                    return
                }
            }
            axios.post("/bwrite/api/OutsourcedUnits/CreateOutsourcedUnits", form).then(ter => {
                if (ter.data.code > 0) {
                    ElMessage.success("添加成功")
                  router.push("/OutsourcedUnitsList")
                } else {
                    ElMessage.error("添加失败")
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
//钩子函数
onMounted(async () => {
         //外协单位地址
    const res = await fetchData('src/data/city.json'); // 假设这个函数是定义好的，负责获取城市数据
    if (res) {
        provinces.value = res; // 假设 res 是一个包含省的数组
        // 设置选择项
        const province = provinces.value.find(p => p.provinceName === form.startingProvince);
        if (province) {
            selectedProvince.value = province.provinceCode;
            onProvinceChange(); // 更新城市和区
            const city = cities.value.find(c => c.provinceName === form.startingCity);
            if (city) {
                selectedCity.value = city.provinceCode;
                onCityChange(); // 更新区
                const county = counties.value.find(c => c.provinceName === form.startingCounty);
                if (county) {
                    selectedCounty.value = county.provinceCode;
                }
            }
        }
    }
})
</script>

 



